package baiqi.sishen.community.schedule;

import baiqi.sishen.community.cache.HotTagCache;
import baiqi.sishen.community.mapper.CommentMapper;
import baiqi.sishen.community.mapper.QuestionMapper;
import baiqi.sishen.community.model.Comment;
import baiqi.sishen.community.model.CommentExample;
import baiqi.sishen.community.model.Question;
import baiqi.sishen.community.model.QuestionExample;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * 计算各个标签的权重
 *
 * @author 兕神
 * @version 1.0
 * DateTime: 2023/5/5
 */

@Component
@Slf4j
public class HotTagTasks {

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private HotTagCache hotTagCache;


    //权重计算priority=questionCount*5+commentCount*1
    @Scheduled(fixedRate = 1000 * 60 * 60 * 3)//运行项目就运行的注解
    public void hotTagSchedule() {
        int offset = 0;
        int limit = 20;
        log.info("hotTagSchedule start {}", new Date());
        List<Question> list = new ArrayList<>();

        Map<String, Long> priorities = new HashMap<>();
        while (offset == 0 || list.size() == limit) {
            list = questionMapper.selectByExampleWithRowbounds(new QuestionExample(), new RowBounds(offset, limit));
            for (Question question : list) {
                CommentExample example = new CommentExample();
                example.createCriteria().andParentIdEqualTo(question.getId());
                List<Comment> comments = commentMapper.selectByExample(example);
                Long count = 0L;
                for (Comment comment : comments) {
                    count += comment.getCommentCount();
                }
                String[] tags = StringUtils.split(question.getTag(), ",");
                for (String tag : tags) {
                    Long priority = priorities.get(tag);
                    if (priority != null) {
                        priorities.put(tag, priority + 5 * question.getCommentCount() + count);
                    } else {
                        priorities.put(tag, 5 * question.getCommentCount() + count);
                    }
                }
            }
            offset += limit;
        }
        hotTagCache.updateTags(priorities);
        log.info("hotTagSchedule stop {}", new Date());
    }
}
